package com.hk.service.impl;

import com.hk.dao.NewsDao;
import com.hk.model.Document;
import com.hk.model.News;
import com.hk.model.NewsType;
import com.hk.service.INewsService;
import com.hk.service.INewsTypeService;
import com.hk.utils.DateUtils;
import com.hk.utils.Io;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: KangWang
 * Date: 2021/5/20 10:50
 * State：新闻业务逻辑层
 */
public class NewsServiceImpl implements INewsService {

    List<News> newsList = null;

    @Override
    public List<News> findAllNews(String path) {
        NewsDao newsDao = new NewsDao();
        newsList = newsDao.findAllNews();
//      1、存储路径  2、文件夹 3、文件
        Document document = new Document(path, "News", "News.txt");
//        检索存储路径和文件夹或文件是否存在或创建 写入数据
        writeData(newsList, document);
//        读取数据
        newsList = (List<News>) readData(document);
//        获取新闻类型
        INewsTypeService iNewsTypeService = new NewsTypeServiceImpl();
        List<NewsType> newsTypes = iNewsTypeService.findAllNewsType(path);
        if (newsList == null && newsList.isEmpty()) {
            System.out.println("暂无新闻");
            return null;
        }
        //            判断新闻属于哪个新闻类型
        for (NewsType newsType : newsTypes) {
            for (News news : newsList) {
                if (newsType.getTypeId() == news.getTypeId()) {
                    news.setNewsType(newsType);
                }
            }
        }
        return newsList;
    }

    /**
     * 读取数据
     *
     * @param document
     * @return
     */
    @Override
    public List<?> readData(Document document) {
        //    根据该对象内多少属性进行转化划分
        final int count = 7;
        newsList = new ArrayList<>();
        List<String> list1 = Io.readData(document);
        for (int i = 0; i < list1.size(); i = i + count) {
            News news = new News(
                    Integer.parseInt(list1.get(i)),
                    list1.get(i + 1),
                    list1.get(i + 2),
                    list1.get(i + 3),
                    DateUtils.stringDate(list1.get(i + 4)),
                    Integer.parseInt(list1.get(i + 5)),
                    Integer.parseInt(list1.get(i + 6))
            );
            newsList.add(news);
        }
        return newsList;
    }

    /**
     * 写入数据
     *
     * @param list
     * @param document
     */
    @Override
    public void writeData(List<?> list, Document document) {
        newsList = (List<News>) list;
        List<String> list1 = new ArrayList<>(50);
        for (News news : newsList) {
            list1.add(String.valueOf(news.getNewsId()));
            list1.add(news.getNewsTitle());
            list1.add(news.getNewsSubhead());
            list1.add(news.getNewsContent());
            list1.add(DateUtils.dateString(news.getReleaseDate()));
            list1.add(String.valueOf(news.getHits()));
            list1.add(String.valueOf(news.getTypeId()));
        }
        Io.writeData(list1, document);
    }
}
